import React, { useState, useEffect } from 'react';
import { Row, Col, Button, Alert, Input, Table, Tooltip, message } from 'antd';
import Fields from './fields';
import { AUDIT } from 'src/utils/constant';
import services from 'src/services/api';
import Question from 'src/components/Question';
import '../../OuterList/index.less';

const { Search } = Input;
export default function(props) {
  const [activeRow, setActivRow] = useState({});
  const [appId, setAppId] = useState('');
  const [eventId, setEventId] = useState('');
  const [mappingRelation, setMappingRelation] = useState([]);
  const [modelLists, setModelLists] = useState([]);
  const [result, setResult] = useState([]);
  // const [fieldLists, setFieldLists] = useState([]);

  const { actionType } = props

  useEffect(() => {
    getModelLists();
    if (actionType === 'child-update') {
      const { childRecord } = props
      setAppId(childRecord.app_id)
      setEventId(childRecord.event_id)
      getParamsMapRelation(childRecord.app_id, childRecord.event_id)
    }
  }, []);

  // 模型参数列表
  function getModelLists() {
    services.model
      .getParticipationParams({
        in_or_out: 0,
        model_list_id: props.record.model_list_id,
      })
      .then((res) => {
        if (res.code === 0) {
          setModelLists(res.data.list);
          getResult(res.data.list, '');
          setActivRow(res.data.list[0]);
        }
      });
  }

  // 关系列表
  function getParamsMapRelation(app_id, event_id) {
    services.model
      .getParamsMapRelation({
        model_list_id: props.record.model_list_id,
        app_id,
        event_id,
      })
      .then((res) => {
        if (res.code === 0) {
          const data = res.data.map((it) => {
            it.var_id_type = it.var_id + '-' + it.var_type;
            it.column_code = it.param_code;
            return it;
          });
          setMappingRelation(data);
        }
      });
  }

  function getResult(data, keyword) {
    const result = data.filter(
      (it) => it.column_code.indexOf(keyword) !== -1 || it.column_name.indexOf(keyword) !== -1
    );
    setResult(result);
  }

  function updateMap(selected, app_id, event_id, product_id) {
    const item = {
      app_id,
      event_id,
      product_id,
      param_id: activeRow.param_id,
      column_code: activeRow.column_code,
      var_id: selected.var_id,
      var_id_type: selected.var_id_type,
      var_code: selected.var_code,
      var_type: selected.var_type,
      var_name: selected.var_name,
    };

    const isExistSelected = mappingRelation.find((it) => {
      return (
        it.app_id === item.app_id &&
        it.event_id === item.event_id &&
        it.column_code === item.column_code &&
        it.param_id === item.param_id
      );
    });
    // 如果已经存在左侧选择的项,则更新所选的指标
    if (isExistSelected) {
      isExistSelected.var_id = item.var_id;
      isExistSelected.var_code = item.var_code;
      isExistSelected.var_type = item.var_type;
      isExistSelected.var_id_type = item.var_id_type;
      isExistSelected.var_name = item.var_name;
    } else {
      mappingRelation.push(item);
    }
    setMappingRelation(JSON.parse(JSON.stringify(mappingRelation)));
  }
  function updateAppAndEvent(app_id, event_id) {
    setAppId(app_id);
    setEventId(event_id);
    setMappingRelation([])
    // getParamsMapRelation(app_id, event_id);
  }
  function handleSubmit() {
    const group = [];
    mappingRelation.forEach((it) => {
      const item = {
        app_id: it.app_id,
        event_id: it.event_id,
        product_id: it.product_id
      };
      const relationsItem = {
        param_id: it.param_id,
        var_id: it.var_id,
        param_code: it.column_code,
        var_code: it.var_code,
        var_id_type: it.var_id_type,
        var_type: it.var_type,
      };
      const current = group.find((it) => it.app_id === item.app_id && it.event_id === item.event_id);
      // 如果group中已经存在这个item
      if (current) {
        relationsItem.var_id &&
          relationsItem.var_code &&
          relationsItem.var_id_type &&
          current.relations.push(relationsItem);
      } else {
        group.push({
          ...item,
          relations: relationsItem.var_id && relationsItem.var_code ? [relationsItem] : [],
        });
      }
    });
    if (!group[0] || group[0].relations.length === 0) return message.warning('映射关系不能为空');
    const params = {
      model_list_id: props.record.model_list_id,
      params: group.map((it) => {
        it.relations = it.relations.map((item) => {
          delete item.var_id_type;
          return item;
        });

        return it;
      }),
    };
    const type = actionType === 'child-update' ? 'paramsMapEdit' : 'paramsMap'
    services.model[type](params).then((res) => {
      if (res.code === 0) {
        message.success(res.msg);
        props.closeModal && props.closeModal();
      } else {
        message.error(res.msg);
      }
    });
  }
  function onRow(record) {
    return {
      onClick: () => {
        if (props.record.audit_status === AUDIT._WAIT) {
          return;
        }
        setActivRow(record);
      },
    };
  }
  const columnsMap = [
    {
      title: '字段/指标名称',
      dataIndex: 'column_name',
      key: 'column_name',
      render: (text) => (
        <Tooltip title={text} placement='topLeft'>
          <div className='overflowtext'>{text}</div>
        </Tooltip>
      ),
    },

    {
      title: '类型',
      dataIndex: 'column_type',
      key: 'column_type',
      render: (text) => (
        <Tooltip title={text} placement='topLeft'>
          <div className='overflowtext'>{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '映射字段',
      dataIndex: 'mapping',
      key: 'mapping',
      width: '150px',
      ellipsis: true,
      render: (text, record) => {
        const current = mappingRelation.find((it) => {
          return (
            it.column_code === record.column_code &&
            it.param_id === record.param_id &&
            it.app_id === appId &&
            it.event_id === eventId
          );
        });
        const fieldName = current ? current.var_name : '';
        return (
          <Tooltip title={fieldName}>
            <div className='overflowtext' style={{ width: '100%' }}>
              {fieldName}
            </div>
          </Tooltip>
        );
      },
    },
  ];

  function onChangePagination(page, pageSize) {
    const index = (page - 1) * pageSize;
    setActivRow(result[index]);
  }

  function smartMap() {
    if (!eventId) {
      message.warning('请选择事件');
      return;
    }
    const params = {
      model_list_config_id: props.record.model_list_config_id,
      app_id: appId,
      event_id: eventId,
    };
    services.model.intelligent(params).then((res) => {
      if (!res.code) {
        const list = res.data.map((it) => {
          it.app_id = appId;
          it.event_id = eventId;
          it.var_id_type = it.var_id + '-' + it.var_type;
          return it;
        });

        setMappingRelation(list);
      } else {
        setMappingRelation([]);
        message.error(res.msg);
      }
    });
  }

  return (
    <div className='tantuer'>
      <Row gutter={20}>
        {props.record.audit_status === AUDIT._WAIT && (
          <Col span={24} style={{ marginBottom: '20px' }}>
            <Alert message='当前映射关系处于待审核状态，暂时无法修改！' type='warning' />
          </Col>
        )}
        <Col span={24} style={{ marginBottom: '20px' }}>
          <Row type='flex' justify='end'>
            <Col>
              <Button type='primary' onClick={() => smartMap()} disabled={props.record.audit_status === AUDIT._WAIT}>
                智能映射
              </Button>
              <Question title='智能映射自动将模型入参、风控事件里名称相同的字段/指标进行映射' />
            </Col>
          </Row>
        </Col>
        <Col span={10}>
          <div className='map-origin'>
            <span>模型入参字段</span>
            <Search
              placeholder='请输入字段名进行搜索'
              onSearch={(value) => {
                getResult(modelLists, value);
              }}
              allowClear
            />
            <Table
              rowClassName={(record) => {
                return record.column_code === activeRow.column_code ? 'active-row' : '';
              }}
              columns={columnsMap}
              dataSource={result}
              onRow={onRow}
              rowKey='column_code'
              className='fixed'
              pagination={{
                onChange: onChangePagination,
                showQuickJumper: true,
                size: 'small',
              }}
            />
          </div>
        </Col>
        <Col span={14}>
          <div className='map-origin'>
            <span>风控字段/指标</span>
            <Fields
              updateMap={updateMap}
              updateAppAndEvent={updateAppAndEvent}
              activeRow={activeRow}
              mapping_relation={mappingRelation}
              disabled={props.record.audit_status === AUDIT._WAIT}
              rowKey='var_id'
              actionType={props.actionType}
              childRecord={props.childRecord}
              record={props.record}
            />
          </div>
        </Col>
        <Col span={24} style={{ textAlign: 'center', margin: '2rem 0' }}>
          <Button
            type='primary'
            onClick={handleSubmit}
            className='marl10'
            autoFocus={true}
            disabled={props.record.audit_status === AUDIT._WAIT}
          >
            确定
          </Button>
        </Col>
      </Row>
    </div>
  );
}
